"""
@Author：十
@Time：2025/9/9 17:25
@FileName：SVR.py
@Description：创建预测模型
"""
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 300e-6, 2000)  # 0~300μs
V0 = 1.0  # 标幺值峰值
tau1, tau2 = 3e-5, 80e-6  # 时间常数调整波头/波尾
V = V0 * (np.exp(-t/tau2) - np.exp(-t/tau1))

# 找到波峰位置（最大值点）[1,2](@ref)
peak_idx = np.argmax(V)
t_peak = t[peak_idx]

# 添加衰减抖动参数
damp_freq = 1e6  # 抖动频率 1MHz
damp_decay = 2e-5  # 衰减时间常数
damp_amp = 0.2 * V0  # 抖动幅度（峰值20%）

# 创建衰减抖动波形（只在波峰后出现）[4,6](@ref)
damp_osc = np.zeros_like(t)
for i in range(len(t)):
    if t[i] >= t_peak:  # 仅波峰后添加抖动
        # 阻尼振荡公式：A * exp(-(t-t0)/τ) * sin(2πf(t-t0))
        damp_osc[i] = damp_amp * np.exp(-(t[i]-t_peak)/damp_decay) * np.sin(2*np.pi*damp_freq*(t[i]-t_peak))

# 组合原始波形和抖动波形
V_combined = V + damp_osc

# 创建图形
plt.figure(figsize=(10, 6))
plt.plot(t*1e6, V, 'b--', label='  ', alpha=0.7)
plt.plot(t*1e6, V_combined, 'r-', label=' ')
plt.plot(t*1e6, damp_osc, 'g:', label=' ', alpha=0.5)

ax = plt.gca()
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])

plt.grid(True)
plt.legend()
plt.show()

from PyQt5.QtCore import QTime, QDateTime

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 600e-6, 2000)  # 0~100μs
V0 = 0.7  # 标幺值峰值
tau1, tau2 = 3e-5, 50e-6  # 时间常数调整波头/波尾
V = V0 * (np.exp(-t/tau2) - np.exp(-t/tau1))

plt.plot(t*1e6, V)
ax = plt.gca()

ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])

# plt.ylim((-1, 1))

plt.grid()
plt.show()

import pandas as pd
import numpy as np
from sklearn.svm import SVR
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
matplotlib.rcParams['font.family'] = 'SimHei'  # 或其他支持中文的字体
matplotlib.rcParams['axes.unicode_minus'] = False
data = pd.read_excel('C:\\Users\\Administrator\\Desktop\\date.xlsx')

# df = pd.read_excel('date.xlsx', sheet_name='Sheet1')
df = pd.DataFrame(data)

# 数据预处理
X = df[['外部温度', '环境温度']]
y = df['内部温度']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 数据标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# 超参数网格搜索
param_grid = {
    'C': [0.1, 1, 10, 100],
    'epsilon': [0.01, 0.1, 0.5, 1],
    'kernel': ['linear', 'rbf', 'poly']
}

# 创建SVR模型并优化参数
svr = GridSearchCV(SVR(), param_grid, cv=5, scoring='neg_mean_squared_error', n_jobs=-1)
svr.fit(X_train_scaled, y_train)

# 获取最佳模型
best_svr = svr.best_estimator_
print(f"最佳参数: {svr.best_params_}")
print(f"训练分数: {best_svr.score(X_train_scaled, y_train):.4f}")

# 测试集评估
y_pred = best_svr.predict(X_test_scaled)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"测试集MSE: {mse:.4f}")
print(f"测试集R²: {r2:.4f}")

# 特征重要性分析（仅适用于线性核）
if best_svr.kernel == 'linear':
    coefs = best_svr.coef_
    features = X.columns
    importance = pd.Series(coefs.ravel(), index=features)
    print("\n特征重要性分析:")
    print(importance.sort_values(ascending=False))

# 结果可视化
plt.figure(figsize=(10, 6))
plt.scatter(y_test, y_pred, alpha=0.6)
plt.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=2)
plt.xlabel('实际内部温度')
plt.ylabel('预测内部温度')
plt.title('SVR预测效果对比 (测试集)')
plt.grid(True)
plt.show()

# 预测误差分布
residuals = y_test - y_pred
plt.figure(figsize=(10, 6))
plt.scatter(y_pred, residuals, alpha=0.6)
plt.axhline(y=0, color='r', linestyle='-')
plt.xlabel('预测内部温度')
plt.ylabel('预测误差')
plt.title('预测误差分布')
plt.grid(True)
plt.show()